//
//  UDRegViewController.swift
//  Chatter
//
//  Created by David on 16/7/13.
//  Copyright © 2016年 David. All rights reserved.
//  注册


import UIKit

@objc protocol UDLoginRegDelegate {
    optional func doubleDismissRegView()
}

class UDRegViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate {

    let GOTO_LOGIN_ALERT_ID = 101
    
    private var tableView:UITableView!
    var navigationBar:UINavigationBar!
    
    private var emailTextField:UDTextField!
    private var passwordTextField:UDTextField!
    private var verifyTextField:UDTextField!
    //private var verifyImg:UIButton!
    private var registerBtn:UIButton!
    private var msg:UILabel!
    
    private var spinnerBG:UIView!
    
    var delegate: UDLoginRegDelegate?
    
    //register compare with login
    
    private var passwordConfirmTextField:UDTextField!
    private var getSmsCodeBtn: UIButton!

    private var sendSmsCountDown = 60
    
    // DEL: private var forgetPswBtn:UIButton!
    // DEL: requireVerify:Bool
    // DEL: func checkNeedVerify()
    
    /*
    @objc private func refreshVerifyImg(){
        NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.GET_VERIFY)")!), queue: NSOperationQueue(), completionHandler: { (resp:NSURLResponse?, returnData:NSData?, err:NSError?) in
            if err == nil{
                if let data = returnData{
                    dispatch_async(dispatch_get_main_queue(), {
                        self.verifyImg.setImage(UIImage(data: data), forState: .Normal)
                        self.spinnerBG.alpha = 0
                    })
                }
            }
        })
    }
    */
    
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        self.modalTransitionStyle = .CrossDissolve
        
        
        tableView = UITableView(frame: CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height - 64), style: .Grouped)
        tableView.keyboardDismissMode = .OnDrag
        tableView.allowsSelection = false
        self.view.addSubview(tableView)
        
        msg = UILabel(frame: CGRect(x: 0, y: 40, width: self.view.frame.width, height: 24))
        msg.textAlignment = .Center
        msg.font = UIFont.systemFontOfSize(12)
        
        msg.textColor = UIColor.brownColor()
        msg.backgroundColor = UIColor.orangeColor()
        msg.alpha = 0
        msg.center.y = 52
        view.addSubview(msg)
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .Black
        navigationBar.barTintColor = Fatcat.THEME_COLOR
        navigationBar.tintColor = UIColor.whiteColor()
        let navItem = UINavigationItem(title: "注册")
        navigationBar.pushNavigationItem(navItem, animated: true)
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(UDRegViewController.dismissAll))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: .Plain, target: self, action: #selector(UDRegViewController.gotoLogin))
        
        emailTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        emailTextField.boderWidth = 0
        emailTextField.placeholder = "11位手机号"
        emailTextField.keyboardType = .NumberPad
        emailTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        
        verifyTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 96, height: 32))
        verifyTextField.boderWidth = 0
        verifyTextField.textFieldType = .Verify
        verifyTextField.placeholder = "手机验证码"
        verifyTextField.keyboardType = .NumberPad
        verifyTextField.tabIndex = 1
        verifyTextField.returnKeyType = .Next
        verifyTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        
        getSmsCodeBtn = UIButton(frame: CGRect(x: self.view.frame.width - 80, y: 0, width: 80, height: 48))
        getSmsCodeBtn.setTitle("获取验证码", forState: .Normal)
        getSmsCodeBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        getSmsCodeBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
        getSmsCodeBtn.backgroundColor = Fatcat.THEME_COLOR
        getSmsCodeBtn.addTarget(self, action: #selector(UDRegViewController.getSmsCode(_:)), forControlEvents: .TouchUpInside)
        
        passwordTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        passwordTextField.boderWidth = 0
        passwordTextField.textFieldType = .Password
        passwordTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        passwordTextField.placeholder = "设置密码"
        passwordTextField.tabIndex = 2
        
        passwordConfirmTextField = UDTextField(frame: CGRect(x: 16, y: 8, width: self.view.frame.width - 32, height: 32))
        passwordConfirmTextField.boderWidth = 0
        passwordConfirmTextField.textFieldType = .Password
        passwordConfirmTextField.tabIndex = 3
        passwordConfirmTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), forControlEvents: .EditingDidEndOnExit)
        passwordConfirmTextField.placeholder = "确认密码"
        passwordConfirmTextField.addTarget(self, action: #selector(UDRegViewController.scrollUpTextField(_:)), forControlEvents: .EditingDidBegin)
        
        /*
        verifyImg = UIButton(frame: CGRect(x: self.view.frame.width - 91.2, y: 24 + emailTextField.frame.height + 8 + passwordTextField.frame.height + 8 + passwordConfirmTextField.frame.height + 8 + verifyTextField.frame.height + 8, width: 83.2, height: 32))
        verifyImg.backgroundColor = UIColor.grayColor()
        verifyImg.contentMode = .ScaleToFill
        verifyImg.addTarget(self, action: #selector(UDRegViewController.refreshVerifyImg), forControlEvents: .TouchUpInside)
        */
        
        
        registerBtn = UIButton(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 48))
        registerBtn.setTitle("注册", forState: .Normal)
        registerBtn.backgroundColor = Fatcat.THEME_COLOR
        registerBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        registerBtn.addTarget(self, action: #selector(UDRegViewController.register), forControlEvents: .TouchUpInside)
        registerBtn.adjustsImageWhenDisabled = true
        
        
        spinnerBG = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinnerBG.center = view.center
        spinnerBG.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinnerBG.layer.cornerRadius = 5
        view.addSubview(spinnerBG)
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = CGPoint(x: 25, y: 25)
        spinner.activityIndicatorViewStyle = .White
        spinner.startAnimating()
        spinnerBG.addSubview(spinner)
        spinnerBG.alpha = 0
        //refreshVerifyImg()
        
//        self.scrollView.addSubview(self.emailTextField)
//        self.scrollView.addSubview(self.passwordTextField)
//        self.scrollView.addSubview(self.passwordConfirmTextField)
//        self.scrollView.addSubview(self.verifyTextField)
//        self.scrollView.addSubview(self.verifyImg)
//        self.scrollView.addSubview(self.registerBtn)
//        self.scrollView.addSubview(self.msg)
        self.emailTextField.becomeFirstResponder()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(UDRegViewController.resendSmsTimer), userInfo: nil, repeats: true)
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 4
        }
        return 1
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 48
    }
    /*
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 32
        }
        if section == 1{
            return 1
        }
        return 0
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0{
            return msg
        }
        return nil
    }
    */
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "row")
        if indexPath.section == 0{
            switch indexPath.row {
            case 0:
                cell.addSubview(emailTextField)
                break
            case 1:
                cell.addSubview(verifyTextField)
                cell.addSubview(getSmsCodeBtn)
                break
            case 2:
                cell.addSubview(passwordTextField)
                break
            case 3:
                cell.addSubview(passwordConfirmTextField)
                break
            default:
                break
            }
        }else if indexPath.section == 1 && indexPath.row == 0 {
            cell.addSubview(registerBtn)
        }
        return cell
    }
    
    @objc private func nextInput(sender: UDTextField){
        switch sender.tabIndex {
        case 0:
            verifyTextField.becomeFirstResponder()
            break
        case 1:
            passwordTextField.becomeFirstResponder()
            break
        case 2:
            passwordConfirmTextField.becomeFirstResponder()
            break
        case 3:
            register()
            break
        default:
            break
        }
    }
    
    func getSmsCode(sender: UIButton){
        if emailTextField.text == ""{
            setErrorMsg("请输入手机号码")
            emailTextField.becomeFirstResponder()
            return
        }
        if emailTextField.text?.characters.count != 11{
            setErrorMsg("手机号码不正确")
            emailTextField.becomeFirstResponder()
            return
        }else{
            
            if NSString(string: emailTextField.text!).substringToIndex(1) != "1"{
                setErrorMsg("手机号码不正确")
                emailTextField.becomeFirstResponder()
                return
            }else{
                if Int64(emailTextField.text!) == nil {
                    setErrorMsg("手机号码不正确")
                    emailTextField.becomeFirstResponder()
                    return
                }
            }
        }
        setErrorMsg("")
        emailTextField.resignFirstResponder()
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        resq.HTTPBody = NSString(string: "act=sendSms&phoneNum=\(emailTextField.text!)").dataUsingEncoding(NSUTF8StringEncoding)
        NSURLSession.sharedSession().dataTaskWithRequest(resq) { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
            var failed = true
            if err == nil {
                if let data = reData {
                    print(NSString(data: data, encoding: NSUTF8StringEncoding))
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
                    if jsonObj?.objectForKey("code") != nil {
                        let reCode = jsonObj?.objectForKey("code") as! Int
                        if reCode == 200 {
                            failed = false
                            dispatch_async(dispatch_get_main_queue(), {
                                self.getSmsCodeBtn.enabled = false
                            })
                        }else if reCode == 202 {
                            failed = false
                            dispatch_async(dispatch_get_main_queue(), {
                                let alert = UIAlertView(title: "用户已注册", message: nil, delegate: nil, cancelButtonTitle: "取消")
                                alert.tag = self.GOTO_LOGIN_ALERT_ID
                                alert.addButtonWithTitle("去登录")
                                alert.delegate = self
                                alert.show()
                            })
                        }
                    }
                }
            }
            if failed {
                dispatch_async(dispatch_get_main_queue(), { 
                    UIAlertView(title: "发送失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
        }.resume()
        
    }
    
    @objc private func register(){
        if checkInput() {
            postRequest()
        }
    }

    
    private func checkInput() ->Bool{
        tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        if emailTextField.text == ""{
            setErrorMsg("请输入手机号码")
            emailTextField.becomeFirstResponder()
            
            return false
        }
        
        // MARK: 打开这段代码检查邮箱地址
        /*
        if emailTextField.text!.componentsSeparatedByString("@").count != 2{
            setErrorMsg("邮箱地址不正确")
            emailTextField.becomeFirstResponder()
            return false
        }
 */
        if emailTextField.text?.characters.count != 11{
            setErrorMsg("手机号码不正确")
            emailTextField.becomeFirstResponder()
            return false
        }else{
            if NSString(string: emailTextField.text!).substringToIndex(1) != "1"{
                setErrorMsg("手机号码不正确")
                emailTextField.becomeFirstResponder()
                return false
            }else{
                if Int64(emailTextField.text!) == nil {
                    setErrorMsg("手机号码不正确")
                    emailTextField.becomeFirstResponder()
                    return false
                }
            }
        }
        
        
        
        if passwordTextField.text == ""{
            setErrorMsg("请输入密码")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        // MARK: 打开这段代码检查密码长度
        
        if passwordTextField.text?.characters.count < 6{
            setErrorMsg("密码长度不足")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        if passwordTextField.text?.characters.count > 16{
            setErrorMsg("密码长度太长")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        if passwordTextField.text != passwordConfirmTextField.text{
            setErrorMsg("两次密码不一致")
            passwordConfirmTextField.becomeFirstResponder()
            return false
        }
        
        if verifyTextField.text == ""{
            setErrorMsg("请输入验证码")
            verifyTextField.becomeFirstResponder()
            return false
        }else{
            if Int64(verifyTextField.text!) == nil {
                setErrorMsg("输入的验证码不合法")
                verifyTextField.becomeFirstResponder()
                return false
            }
        }
        setErrorMsg("")
        
        return true
    }
    
    private func postingStatus(status: Bool){
        
        emailTextField.enabled = !status
        passwordTextField.enabled = !status
        passwordConfirmTextField.enabled = !status
        verifyTextField.enabled = !status
        //verifyImg.enabled = !status
        registerBtn.enabled = !status
        if status{
            spinnerBG.alpha = 1
        }else{
            spinnerBG.alpha = 0
        }
    }
    
    private func postRequest(){
        postingStatus(true)
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        resq.HTTPBody = NSString(string: "act=regist&phoneNum=\(emailTextField.text!)&password=\(passwordTextField.text!)&checkCode=\(verifyTextField.text!)").dataUsingEncoding(NSUTF8StringEncoding)
        
        NSURLConnection.sendAsynchronousRequest(resq, queue: NSOperationQueue()) { (resp:NSURLResponse?, returnData:NSData?, err:NSError?) in
            if err == nil{
                if let data = returnData{
                    dispatch_async(dispatch_get_main_queue(), { 
                        self.handleResult(data)
                    })
                    return
                }
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.setErrorMsg("网络错误")
                self.postingStatus(false)
            })
            
        }
    }
    
    private func handleResult(res: NSData){
        print(NSString(data: res, encoding: NSUTF8StringEncoding))
        
        let jsonObj = try? NSJSONSerialization.JSONObjectWithData(res, options: .AllowFragments) as! NSDictionary
        if jsonObj != nil{
            if jsonObj?.objectForKey("code") != nil{
                let reCode = jsonObj?.objectForKey("code") as! Int
                if reCode == 200 {
                    // MARK: 注册完成  保存登陆信息
                    NSUserDefaults.standardUserDefaults().setObject(emailTextField.text!, forKey: "user")
                    NSUserDefaults.standardUserDefaults().setObject(true, forKey: "orderListRefreshRequire")
                    let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
                    let cookiesData = NSKeyedArchiver.archivedDataWithRootObject(cookies)
                    
                    NSUserDefaults.standardUserDefaults().setObject(cookiesData, forKey: "cookies")
                    NSUserDefaults.standardUserDefaults().synchronize()
                    dismissViewControllerAnimated(false, completion: nil)
                    delegate?.doubleDismissRegView?()
                }else{
                    setErrorMsg(jsonObj?.objectForKey("message") as! String)
                    postingStatus(false)
                }
                
                return
            }
        }
        setErrorMsg("json error")
        postingStatus(false)
        
    }

    private func setErrorMsg(message: String){
        msg.text = message
        if message != ""{
            self.msg.alpha = 1
            UIView.animateWithDuration(0.3, delay: 0, options: .CurveLinear, animations: {
                
                self.msg.center.y = 76
                }, completion: { (finished) in
                    UIView.animateWithDuration(0.3, delay: 3, options: .CurveLinear, animations: {
                        self.msg.center.y = 52
                        }, completion: { (finished1) in
                            self.msg.alpha = 0
                    })
            })
        }
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if alertView.tag == GOTO_LOGIN_ALERT_ID{
            if buttonIndex == 1{
                dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    
    @objc private func gotoLogin(){
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    func dismissAll(){
        dismissViewControllerAnimated(false, completion: nil)
        delegate?.doubleDismissRegView?()
    }
    
    func resendSmsTimer(){
        if !getSmsCodeBtn.enabled {
            if sendSmsCountDown < 0{
                getSmsCodeBtn.setTitle("获取验证码", forState: .Normal)
                getSmsCodeBtn.enabled = true
                sendSmsCountDown = 60
                return
            }
            getSmsCodeBtn.setTitle("\(sendSmsCountDown)s", forState: .Normal)
            sendSmsCountDown -= 1
        }
        
    }
    
    func scrollUpTextField(sender:UITextField){
        print(tableView.contentOffset.y)
        if tableView.contentOffset.y <= 0 {
            tableView.setContentOffset(CGPoint(x: 0, y: 64), animated: true)
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
